//
//  SNRepairAskController.m
//  app
//
//  Created by 王少宁 on 15/8/26.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "SNRepairAskController.h"
#import "SNDeteSelectView.h"
#import "SNRepairAskDataManager.h"
#import "SNRepairAskSubmitModel.h"
#import "SNRepairTypeView.h"
#import "UIImage+Conveniently.h"


#import "HDBtnDemoVC.h"

@interface SNRepairAskController () <UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

/** 联系人*/
@property (nonatomic, retain) UITextField * contactTextField;
/** 手机号*/
@property (nonatomic, retain) UITextField * phoneNumTextField;
/** 预约开始时间*/
@property (nonatomic, retain) UIButton * bespeakTimeBtnOne;
/** 预约结束时间*/
@property (nonatomic, retain) UIButton * bespeakTimeBtnTwo;
/** 报修地址*/
@property (nonatomic, retain) UITextField * repairAddressTextField;
/** 报修项目*/
@property (nonatomic, retain) UIButton * repairTypeBtn;
/** 报修内容*/
@property (nonatomic, retain) UITextView * repairContentTextView;

@property (nonatomic, strong) UIView * picture_mian_view;

@property (nonatomic, retain) UILabel * repairContentPlaceholderLabel;
@property (nonatomic, retain) SNDeteSelectView * dateSelectView;
@property (nonatomic, retain) SNRepairTypeView * repairTypeView;
@property (nonatomic, retain) SNRepairAskDataManager * manager;
@property (nonatomic, retain) SNRepairAskResult * result;
@property (nonatomic, retain) SNSubmitRepairAskResult * submitResult;
@property (nonatomic, strong) SNSubmitPictureResult * subPicResult;

@property (nonatomic, strong) NSMutableArray * image_array;
@property (nonatomic, strong) NSMutableArray * image_view_array;

@property (nonatomic, assign) BOOL isDeleted;

@end

@implementation SNRepairAskController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"维修申请";
    
    self.image_array = [NSMutableArray array];
    self.image_view_array = [NSMutableArray array];
    
    [self createView];
    
    
    
    
    self.manager = [SNRepairAskDataManager shareManager];
    self.result = [[SNRepairAskResult alloc] initWithTarget:self action:@selector(loadDataWithResult:)];
    self.submitResult = [[SNSubmitRepairAskResult alloc] initWithTarget:self action:@selector(submitResult:)];
    self.subPicResult = [[SNSubmitPictureResult alloc]initWithTarget:self action:@selector(subPicRsult:)];
    DLog(@"%@",self.repairAskModel.address_params);
    [self.manager loadDataWirhResult:self.result mallComId:self.repairAskModel.mall_com_id address:self.repairAskModel.address_params];
    
    self.view.nothingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.view viewController:self tryAgain:@selector(tryAgain)];
    [self.view.nothingRefreshView show];
    
    _dateSelectView = [[SNDeteSelectView alloc] initWithFrame:CGRectMake(0, (self.view.ubo.height - 308-UP(1)) * 0.5, SCREEN_WIDTH, 308 + UP(1))];
    [self.view addSubview:_dateSelectView];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadViewWithPicture:) name:@"BaoXiuTakePhoto" object:nil];
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
}


- (void)tryAgain
{
    [self.manager loadDataWirhResult:self.result mallComId:self.repairAskModel.mall_com_id address:self.repairAskModel.address_params];
}

- (void)createView
{
    self.view.backgroundColor = [XCommon hexStringToColor:kColor_m_light_gray_background];
    
    UIView * contactView = [[UIView alloc] init];
    contactView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:contactView];
    
    /** 联系人*/
    UILabel * contactLabel = [[UILabel alloc] init];
    contactLabel.text = @"联  系  人:";
    CGFloat contactLabelW = [XCommon widthForString:contactLabel.text fontSize:13.0f] + 1;
    contactLabel.frame = CGRectMake(10, 10, contactLabelW, 25);
    [contactView addSubview:contactLabel];
    
    _contactTextField = CREATE_WITH_FRAME_OF(UITextField, [contactLabel.ufo fx:1.0 ox:10 fy:0],
                                             [contactLabel.ubo fw:-1.0 ow:SCREEN_WIDTH - 30 fh:1.0]);
    [contactView addSubview:_contactTextField];
    
    /** 联系电话*/
    UILabel * phoneNumLabel = CREATE_WITH_FRAME_OF(UILabel, [contactLabel.ufo fx:0 fy:1.0 oy:10],
                                                   [contactLabel.ubo fw:1.0 fh:1.0]);
    phoneNumLabel.text = @"联系电话:";
    [contactView addSubview:phoneNumLabel];
    
    _phoneNumTextField = CREATE_WITH_FRAME_OF(UITextField, [phoneNumLabel.ufo fx:1.0 ox:10 fy:0],
                                             [_contactTextField.ubo fw:1.0 fh:1.0]);
    [contactView addSubview:_phoneNumTextField];
    
    
    /** 预约时间*/
    UILabel * bespeakTimeLabel = CREATE_WITH_FRAME_OF(UILabel, [phoneNumLabel.ufo fx:0 fy:1.0 oy:10],
                                                      [phoneNumLabel.ubo fw:1.0 fh:1.0]);
    bespeakTimeLabel.text = @"预约时间:";
    [contactView addSubview:bespeakTimeLabel];
    
    NSDateFormatter * formagtter= [[NSDateFormatter alloc] init];
    formagtter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString * nowDateStr = [formagtter stringFromDate:[NSDate date]];
    
    CGFloat bespeakTimeTextFieldW = (_phoneNumTextField.ubo.width - 25) * 0.5;
    
    _bespeakTimeBtnOne = [UIButton buttonWithType:UIButtonTypeCustom];
    _bespeakTimeBtnOne.frame = CGRectOf([bespeakTimeLabel.ufo fx:1.0 ox:10 fy:0],
                                        [bespeakTimeLabel.ubo ow:bespeakTimeTextFieldW fh:1.0]);
    [_bespeakTimeBtnOne setTitle:nowDateStr forState:UIControlStateNormal];
    [_bespeakTimeBtnOne setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _bespeakTimeBtnOne.tag = 1;
    [_bespeakTimeBtnOne addTarget:self action:@selector(showDatePickerWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    [contactView addSubview:_bespeakTimeBtnOne];
    
    UILabel * toLabel = CREATE_WITH_FRAME_OF(UILabel, [_bespeakTimeBtnOne.ufo fx:1.0 ox:5 fy:0],
                                             [_bespeakTimeBtnOne.ubo ow:15 fh:1.0]);
    toLabel.text = @"至";
    toLabel.textAlignment = NSTextAlignmentCenter;
    toLabel.font = JKAppGlobleFontSmallTagText;
    [contactView addSubview:toLabel];
    
    _bespeakTimeBtnTwo = [UIButton buttonWithType:UIButtonTypeCustom];
    _bespeakTimeBtnTwo.frame = CGRectOf([toLabel.ufo fx:1.0 ox:5 fy:0],
                                        [_bespeakTimeBtnOne.ubo fw:1.0 fh:1.0]);
    [_bespeakTimeBtnTwo setTitle:nowDateStr forState:UIControlStateNormal];
    [_bespeakTimeBtnTwo setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _bespeakTimeBtnTwo.tag = 2;
    [_bespeakTimeBtnTwo addTarget:self action:@selector(showDatePickerWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    [contactView addSubview:_bespeakTimeBtnTwo];
    
    contactView.frame = CGRectMake(0, 10 + 64, SCREEN_WIDTH, bespeakTimeLabel.ufo.yy + 10);
    
    
    //提交按钮
    UIButton * submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    submitBtn.frame = CGRectMake(40, ScreenHeight - 50, SCREEN_WIDTH - 80, 40);
    submitBtn.backgroundColor = [XCommon hexStringToColor:@"#f54e52"];
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(submitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:submitBtn];
    
    
    
    UIView * repairView = CREATE_WITH_FRAME_OF(UIView, [contactView.ufo fx:0 fy:1.0 oy:10],
                                               [self.view.ubo ow:SCREEN_WIDTH oh:ScreenHeight - contactView.ufo.yy - 10 - submitBtn.ubo.height - 20]);
    repairView.backgroundColor = [UIColor whiteColor
                                  ];
    [self.view addSubview:repairView];
    
    
    //报修地点
    UILabel * repairAddressLabel = CREATE_WITH_FRAME_OF(UILabel, CGPointMake(10, 10),
                                                        [bespeakTimeLabel.ubo fw:1.0 fh:1.0]);
    repairAddressLabel.text = @"报修地点:";
    [repairView addSubview:repairAddressLabel];
    
    _repairAddressTextField = CREATE_WITH_FRAME_OF(UITextField, [repairAddressLabel.ufo fx:1.0 ox:10 fy:0],
                                             [repairAddressLabel.ubo fw:-1.0 ow:SCREEN_WIDTH - 30 fh:1.0]);
    [repairView addSubview:_repairAddressTextField];
    
    //报修项目
    UILabel * repairTypeLabel = CREATE_WITH_FRAME_OF(UILabel, [repairAddressLabel.ufo fx:0 fy:1.0 oy:10],
                                                     [repairAddressLabel.ubo fw:1.0 fh:1.0]);
    repairTypeLabel.text = @"报修项目:";
    [repairView addSubview:repairTypeLabel];
    
    _repairTypeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _repairTypeBtn.frame = CGRectOf([repairTypeLabel.ufo fx:1.0 ox:10 fy:0],
                                    [_contactTextField.ubo fw:1.0 fh:1.0]);
    [_repairTypeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _repairTypeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _repairTypeBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5);
    [_repairTypeBtn addTarget:self action:@selector(repairTypeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [repairView addSubview:_repairTypeBtn];
    
    //报修内容
    UILabel * repairContentLabel = CREATE_WITH_FRAME_OF(UILabel, [repairTypeLabel.ufo fx:0 fy:1.0 oy:10],
                                                     [repairTypeLabel.ubo fw:1.0 fh:1.0]);
    repairContentLabel.text = @"报修内容";
    [repairView addSubview:repairContentLabel];
    
    _repairContentTextView = CREATE_WITH_FRAME_OF(UITextView, [repairContentLabel.ufo fx:1.0 ox:10 fy:0],[_repairTypeBtn.ubo fw:1.0 oh:(repairView.ubo.height - repairContentLabel.ufo.y - 10)/2]);
    _repairContentTextView.delegate = self;
    [repairView addSubview:_repairContentTextView];
    
    _repairContentPlaceholderLabel = CREATE_WITH_FRAME_OF(UILabel, [_repairContentTextView.ufo fx:0 fy:0],
                                                                   [_repairAddressTextField.ubo fw:1.0 fh:1.0]);
    _repairContentPlaceholderLabel.text = @"请输入申报详情...";
    _repairContentPlaceholderLabel.textColor = [XCommon hexStringToColor:kColor_m_light_gray_text];
    [repairView addSubview:_repairContentPlaceholderLabel];
    
    
    
    self.picture_mian_view = [[UIView alloc]initWithFrame:CGRectOf([_repairContentTextView.ufo fx:1 ox:-(UBO_SCREEN.width-24) fy:1 oy:4], [repairView.ubo ow:UBO_SCREEN.width-24 oh:110])];
    self.picture_mian_view.userInteractionEnabled = YES;
//    self.picture_mian_view.backgroundColor = [UIColor blueColor];
    [repairView addSubview:self.picture_mian_view];
    
    
//    DLog(@"%%%%%%%%%%%%%%%% picview === %@",self.picture_mian_view);
    
    UIButton * xiangce_btn = [[UIButton alloc]initWithFrame:CGRectOf([self.picture_mian_view.ubo fx:0 ox:12 fy:0 oy:4], [self.picture_mian_view.ubo ow:22 oh:20])];
//    xiangce_btn.backgroundColor = [UIColor redColor];
    [xiangce_btn setBackgroundImage:[UIImage imageNamed:@"ic_picture_default"] forState:UIControlStateNormal];
    xiangce_btn.tag = 1;
    [xiangce_btn addTarget:self action:@selector(choose:) forControlEvents:UIControlEventTouchUpInside];
    [self.picture_mian_view addSubview:xiangce_btn];
    
    
    UIButton * xiangji_btn = [[UIButton alloc]initWithFrame:CGRectOf([xiangce_btn.ufo fx:1 ox:12 fy:0 ], [self.picture_mian_view.ubo ow:22 oh:20])];
//    xiangji_btn.backgroundColor = [UIColor redColor];
    [xiangji_btn setBackgroundImage:[UIImage imageNamed:@"ic_camera_default"] forState:UIControlStateNormal];
    xiangji_btn.tag = 2;
    [xiangji_btn addTarget:self action:@selector(choose:) forControlEvents:UIControlEventTouchUpInside];
    [self.picture_mian_view addSubview:xiangji_btn];
    
    CGFloat imageWidth = (self.picture_mian_view.frame.size.width-6*5)/4;
    

    
    for ( int i = 0; i < 4; i++) {
        
        
        UIImageView * iv = [[UIImageView alloc]initWithFrame:CGRectOf([self.picture_mian_view.ubo fx:0 ox:(2*(i+1)+i*imageWidth) fy:1 oy:-imageWidth], [self.picture_mian_view.ubo ow:imageWidth oh:imageWidth])];
//        iv.backgroundColor = [UIColor greenColor];
        iv.userInteractionEnabled = YES;
        iv.tag = i;
        [self.picture_mian_view addSubview:iv];
        
        
        
        UIImageView * x = [[UIImageView alloc]initWithFrame:CGRectOf([iv.ubo fx:1 ox:-34/2 fy:0 ], [iv.ubo ow:34/2 oh:34/2])];
//        x.backgroundColor = [UIColor redColor];
        x.tag = i;
        x.image = [UIImage imageNamed:@"baoxiu_img_delete"];
        x.hidden = YES;
        [iv addSubview:x];
        

        UIButton * btn = [[UIButton alloc]init];
        btn.tag = i;
        btn.frame = iv.bounds;
        [btn addTarget:self action:@selector(picDeleteImage:) forControlEvents:UIControlEventTouchUpInside];
        [iv addSubview:btn];
        btn.hidden = YES;
   
        
        [self.image_view_array addObject:iv];
        
        
    }
    
    
    //统一设置
    contactLabel.font = phoneNumLabel.font = bespeakTimeLabel.font = _contactTextField.font = _phoneNumTextField.font = repairAddressLabel.font = _repairAddressTextField.font = repairTypeLabel.font = _repairTypeBtn.titleLabel.font = repairContentLabel.font = _repairContentTextView.font = _repairContentPlaceholderLabel.font = JKAppGlobleFontSmallTagText;
    _bespeakTimeBtnOne.titleLabel.font = _bespeakTimeBtnTwo.titleLabel.font = [UIFont systemFontOfSize:9.0f];
    
    _contactTextField.borderStyle = _phoneNumTextField.borderStyle = _repairAddressTextField.borderStyle = UITextBorderStyleRoundedRect;
    
    _bespeakTimeBtnOne.layer.borderWidth = _bespeakTimeBtnTwo.layer.borderWidth = _repairTypeBtn.layer.borderWidth = _repairContentTextView.layer.borderWidth = UP(1);
    _bespeakTimeBtnOne.layer.borderColor = _bespeakTimeBtnTwo.layer.borderColor = _repairTypeBtn.layer.borderColor = _repairContentTextView.layer.borderColor = [XCommon hexStringToColor:kColor_gray_line].CGColor;
    _bespeakTimeBtnOne.layer.cornerRadius = _bespeakTimeBtnTwo.layer.cornerRadius = _repairTypeBtn.layer.cornerRadius = _repairContentTextView.layer.cornerRadius = 5;
    
}

- (void)loadDataWithResult:(SNRepairAskResult *)result
{
    if (result.success) {
        [self.view.nothingRefreshView remove];
        [self viewReload];
    } else if (result.failure) {
        [self.view.nothingRefreshView requestAgain];
    }
}

- (void)viewReload
{
    NSMutableString * receiver = [NSMutableString stringWithString:self.repairAskModel.receiver];
    for (int i = 1; i < receiver.length; i++) {
        [receiver replaceCharactersInRange:NSMakeRange(i, 1) withString:@"*"];
    }
    _contactTextField.text = receiver;
    _phoneNumTextField.text = self.repairAskModel.phone;
    _repairAddressTextField.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"fullAddress"];
    SNRepairTypeModel * repairTypeModel = self.result.repairTypeModelsArray.firstObject;
    [_repairTypeBtn setTitle:repairTypeModel.option_name forState:UIControlStateNormal];
    _repairTypeBtn.tag = repairTypeModel.option_value.intValue + kRepairTypeSubBtnBaseTag;
    _repairTypeBtn.titleLabel.text = [NSString stringWithFormat:@"%@",repairTypeModel.com_id];
    _repairTypeBtn.titleLabel.tag = repairTypeModel.root_id.integerValue;
    
    
    UIView * view = _repairTypeBtn.superview;
    CGFloat repairTypeViewH = self.result.repairTypeModelsArray.count * kRepairTypeSubBtnH + (self.result.repairTypeModelsArray.count - 1) * UP(1);
    if (self.result.repairTypeModelsArray.count > 3) {
        repairTypeViewH = kRepairTypeSubBtnH * 4 + UP(3);
    }
    _repairTypeView = [[SNRepairTypeView alloc] initWithFrame:CGRectOf([_repairTypeBtn.ufo fx:0 fy:1.0 oy:view.ufo.y], [_repairTypeBtn.ubo fw:1.0 oh:repairTypeViewH]) repairTypeArray:self.result.repairTypeModelsArray repairTypeBtn:_repairTypeBtn];
//    _repairTypeView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:_repairTypeView];
}

#pragma mark - 点击了选择日期
- (void)showDatePickerWithBtn:(UIButton *)btn
{
    [self allTextFieldResignFirstResponder];
    [self.view bringSubviewToFront:_dateSelectView];
    
    if (btn.tag == 1) {
        [_dateSelectView showWithBtn:_bespeakTimeBtnOne];
    } else if (btn.tag == 2) {
        [_dateSelectView showWithBtn:_bespeakTimeBtnTwo];
    }
}

#pragma mark - 点击了报修项目
- (void)repairTypeBtnClick
{
    [self allTextFieldResignFirstResponder];
    [self.view bringSubviewToFront:_repairTypeView];
    [_repairTypeView show];
}

#pragma mark - 点击了提交按钮
- (void)submitBtnClick
{
    if (!self.repairContentTextView.text.length) {
        [MyToast showDefaultBottonWithText:@"请输入维修详情"];
        return;
    }
    
    SNRepairAskSubmitModel * model = [[SNRepairAskSubmitModel alloc] init];
    model.mall_com_id = self.repairAskModel.mall_com_id;
    model.apply_type = @"3";
    model.apply_name = self.contactTextField.text;
    model.telephone = self.phoneNumTextField.text;
    model.appointment_at = self.bespeakTimeBtnOne.titleLabel.text;
    model.appointment_at_end = self.bespeakTimeBtnTwo.titleLabel.text;
    model.address = self.repairAddressTextField.text;
//    model.repair_item = [NSString stringWithFormat:@"%d",(int)self.repairTypeBtn.tag - kRepairTypeSubBtnBaseTag];
    model.repair_item = self.repairTypeBtn.titleLabel.text;
    model.info = self.repairContentTextView.text;
    model.add_code = [[NSUserDefaults standardUserDefaults]objectForKey:@"fullAddress"];
    model.uid = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
    model.repair_item_id = [NSString stringWithFormat:@"%ld",self.repairTypeBtn.tag-kRepairTypeSubBtnBaseTag];
    model.com_id = self.repairTypeBtn.titleLabel.text;
    model.root_id = [NSString stringWithFormat:@"%d",self.repairTypeBtn.titleLabel.tag];
    
    
//    [MBProgressHUD showMBProgressHUBOnWindowsWithMessage:@"维修申请中..."];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [self.manager submitRepairAskWithResult:self.submitResult repairAskModle:model ImageArray:self.image_array];
}

- (void)submitResult:(SNSubmitRepairAskResult *)result
{
//    [MBProgressHUD dismissMBProgressHUBOnWindows];
    if (result.success) {
        
        if (self.image_array.count > 0) {
             [self uploadPicWithSign:@"0"];
        }else
        {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            [MyToast showWithText:@"维修申请成功"];
            
        }
//        [MBProgressHUD showMBProgressHUBOnWindowsWithMessage:@"维修申请成功"];
       
        
        
//        [self.navigationController popViewControllerAnimated:YES];
    } else if (result.failure) {
//        [MBProgressHUD showMBProgressHUBOnWindowsWithMessage:@"维修申请失败"];
//        [MyToast showDefaultBottonWithText:result.message];
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        [MyToast showWithText:@"维修申请失败"];
        
    }
//    [MBProgressHUD dismissMBProgressHUBOnWindows];
}




-(void)uploadPicWithSign:(NSString*)sign
{

//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSDictionary * dic = [self.image_array objectAtIndex:sign.integerValue];
    
    UIImage * image = dic[@"image"];
    NSData * data = UIImageJPEGRepresentation(image, 0.4);
    NSString * file =  [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    NSDictionary * params = @{@"file":file,
                              @"file_name":dic[@"name"]};
    [self.manager subPicWihtResult:self.subPicResult Params:params Sign:sign.integerValue+1];

}


-(void)subPicRsult:(SNSubmitPictureResult*)rt
{
//    [MBProgressHUD dismissMBProgressHUBOnWindows];
    
    
    
    if (rt.success) {
//        [MBProgressHUD showMBProgressHUBOnWindowsWithMessage:@"维修申请成功"];
        [MyToast showWithText:@"维修申请成功"];

        
        if (rt.sign == self.image_array.count) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            [self.navigationController popViewControllerAnimated:YES];
        }else
        {
            [self uploadPicWithSign:[NSString stringWithFormat:@"%ld",(long)rt.sign]];
            
        }
        
        
        
    } else if (rt.failure) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        [MyToast showWithText:@"维修申请失败"];
//        [MBProgressHUD showMBProgressHUBOnWindowsWithMessage:@"维修申请失败"];
        //        [MyToast showDefaultBottonWithText:result.message];
    }
//    [MBProgressHUD dismissMBProgressHUBOnWindows];
}



- (void)textViewDidBeginEditing:(UITextView *)textView
{
    _repairContentPlaceholderLabel.hidden = YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    if (!textView.text.length) {
        _repairContentPlaceholderLabel.hidden = NO;
    }
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self allTextFieldResignFirstResponder];
}

- (void)allTextFieldResignFirstResponder
{
    [_contactTextField resignFirstResponder];
    [_phoneNumTextField resignFirstResponder];
    [_repairAddressTextField resignFirstResponder];
    [_repairContentTextView resignFirstResponder];
}



-(void)reloadViewWithPicture:(NSNotification*)info
{
    
    for (int i = 0; i < self.image_view_array.count ; i++) {
        
        UIImageView * iv = [self.image_view_array objectAtIndex:i];
        
        iv.image = [UIImage imageNamed:@""];
        
        UIImageView * cancle = [iv.subviews objectAtIndex:0];
        cancle.hidden = YES;
        
        UIButton * btn = [iv.subviews objectAtIndex:1];
        btn.hidden = YES;
    }
    
    
    for (int j = 0; j < self.image_array.count; j++) {
        
        UIImageView * iv = [self.image_view_array objectAtIndex:j];
        NSDictionary * dic = [self.image_array objectAtIndex:j];
        
        iv.image = dic[@"image"];
        
        UIImageView * cancale = [iv.subviews objectAtIndex:0];
        cancale.hidden = NO;
        
        UIButton * btn = [iv.subviews objectAtIndex:1];
        btn.hidden = NO;
        
        
    }
    
    
}



-(void)choose:(UIButton*)sender
{
    

    
    
    if (self.image_array.count < 4) {
        if (sender.tag == 1) {
            //相册
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.delegate = self;
            //设置选择后的图片可被编辑
            //        picker.allowsEditing = YES;
            [picker.navigationBar setTintColor:[UIColor whiteColor]];
            [self presentViewController:picker animated:NO completion:nil];
            
        }else
        {
            
            //相机
            UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
            {
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.delegate = self;
                //设置拍照后的图片可被编辑
                //            picker.allowsEditing = YES;
                picker.sourceType = sourceType;
                
                [self presentViewController:picker animated:NO completion:nil];
            }else
            {
                
            }
        }

    }else
    {
        [MyToast showWithText:@"只能添加四张"];
    }
    
    
}

static int i = 1;

#pragma mark - 保存图片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    NSDate * date = [NSDate date];
    NSString *aTimer = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    DLog(@"date ======  %@",aTimer);
    
    UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
    }
    
    NSString * name ;
    NSDictionary * dic;
//    if (self.isDeleted == YES) {
//        
//        for (int i = 0 ; i < self.image_array.count; i++) {
//            
//            NSDictionary * dic = [self.image_array objectAtIndex:i];
//            
//            if ([dic[@"delete"]integerValue] == 1) {
//                
//                NSString * index = dic[@"index"];
//                name = [NSString stringWithFormat:@"mypic_%@_%@_%@.jpg",index,[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"],aTimer];
//                [self saveImage:image WithName:name];
//                
//                dic = @{@"name":name,
//                                       @"image":image,
//                                       @"delete":@"0",
//                                       @"index":index};
//                
//                [self.image_array replaceObjectAtIndex:index.integerValue withObject:dic];
//                
//                break;
//                
//            }
//            
//        }
//        
//    }
//    else
//    {
        name = [NSString stringWithFormat:@"mypic_%lu_%@_%@.jpg",(unsigned long)self.image_array.count,[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"],aTimer];
    
        [self saveImage:image WithName:name];
        
       dic = @{@"name":name,
                               @"image":image,
                               @"delete":@"0",
                               @"index":[NSString stringWithFormat:@"%lu",(unsigned long)self.image_array.count]};
        [self.image_array addObject:dic];
//    }
    

//    
//    
//    if (self.image_array.count == 4) {
//        i = 1;
//    }
    
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"BaoXiuTakePhoto" object:dic];
    
    [picker dismissViewControllerAnimated:NO completion:nil];
    
    
    

    
    
}
-(UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}


- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    //    NSData * imageData = UIImagePNGRepresentation(tempImage);
    NSData* imageData = [UIImage dataOriginImage:tempImage scaleToSize:CGSizeMake(480, 480) fileToRatio:0.4];
    //    NSData * imageData = [UIImage dataOriginImage:tempImage scaleToSize:CGSizeMake(480, 480) fileToRatio:0.8];
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
}




-(void)picDeleteImage:(UIButton*)sender
{
//    DLog(@"++++++++++++++shanchu");
    

       
        [self.image_array removeObjectAtIndex:sender.tag];
        
        
        for (int i = 0; i < self.image_view_array.count ; i++) {
            
            UIImageView * iv = [self.image_view_array objectAtIndex:i];
            
            iv.image = [UIImage imageNamed:@""];
            
            UIImageView * cancle = [iv.subviews objectAtIndex:0];
            cancle.hidden = YES;
            
            UIButton * btn = [iv.subviews objectAtIndex:1];
            btn.hidden = YES;
            
        }
        
        
        for (int j = 0; j < self.image_array.count; j++) {
            
            UIImageView * iv = [self.image_view_array objectAtIndex:j];
            NSDictionary * dic = [self.image_array objectAtIndex:j];
            
            iv.image = dic[@"image"];
            
            UIImageView * cancale = [iv.subviews objectAtIndex:0];
            cancale.hidden = NO;
            
            UIButton * btn = [iv.subviews objectAtIndex:1];
            btn.hidden = NO;
            
            
        }
        
        
    
    
    
   

    
    
}








-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"BaoXiuTakePhoto" object:nil];

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
